package cn.xd.base.persistence.repository.impl;

import cn.xd.base.basic.type.AppUserThirdPartyId;
import cn.xd.base.domain.entity.AppUserThirdParty;
import cn.xd.base.domain.repository.AppUserThirdPartyRepository;
import cn.xd.base.persistence.dos.AppUserThirdPartyConverter;
import cn.xd.base.persistence.dos.AppUserThirdPartyDO;
import cn.xd.base.persistence.mps.AppUserThirdPartyMpService;
import cn.xd.core.ddd.db.DbRepositorySupport;
import cn.xd.core.ddd.diff.EntityDiff;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;

@Repository
public class AppUserThirdPartyRepositoryImpl extends DbRepositorySupport<AppUserThirdParty, AppUserThirdPartyId> implements AppUserThirdPartyRepository {

    @Resource
    private AppUserThirdPartyMpService appUserThirdPartyMpService;

    @Override
    protected void onInsert(AppUserThirdParty aggregate) {
        appUserThirdPartyMpService.saveResult(aggregate, AppUserThirdPartyConverter.INSTANCE)
                .successAndFailThrow((data) -> aggregate.setId(AppUserThirdPartyId.of(data.getId())));
    }

    @Override
    protected AppUserThirdParty onSelect(AppUserThirdPartyId appUserThirdPartyId) {
        return appUserThirdPartyMpService.getResult(appUserThirdPartyId, AppUserThirdPartyConverter.INSTANCE).get();
    }

    @Override
    protected void onUpdate(AppUserThirdParty aggregate, EntityDiff diff) {
        if (diff.isSelfModified()) {
            AppUserThirdPartyDO bean = diff.getBean(AppUserThirdPartyDO.class);
            appUserThirdPartyMpService.updateResult(bean).failThrow();
        }
    }

    @Override
    protected void onDelete(AppUserThirdParty aggregate) {
        Long appUserThirdPartyId = aggregate.getId().getValue();
        appUserThirdPartyMpService.removeById(appUserThirdPartyId);
    }

}
